package com.lms.utils;

import com.lms.mapper.BookMapper;
import com.lms.mapper.UserDAO;
import java.util.Map;
import java.util.TreeMap;

/**
 * 用于将BorrowRecord的id进行转换
 */
public class BorrowRecordDisplay {
    private Map<Integer, String> userIdMap;
    private Map<Integer, String> bookIdMap;
    public BorrowRecordDisplay() {
        userIdMap = new TreeMap<>();
        bookIdMap = new TreeMap<>();
    }
    /**
     * 将userid转化为username
     *
     * @param userid
     * @return 查找失败返回null
     */
    public String userIdToString(Integer userid) {
        if (userid == null) return null;
        String ret = userIdMap.get(userid);
        if (ret == null) {//进行数据库查找
            UserDAO dao = new UserDAO();
            ret = dao.findNameById(userid);
            if (ret != null)
                userIdMap.put(userid, ret);
        }
        return ret;
    }
    public String bookIDToString(Integer bookID) {
        if (bookID == null) return null;
        String ret = bookIdMap.get(bookID);
        if (ret == null) {//进行数据库查找
            //TODO 通过bookId(BookID)查找书名(Title),未找到返回null
            BookMapper mapper = SqlSessionUtil.openSession().getMapper(BookMapper.class);
            ret = mapper.selectByBookId(bookID);
            if (ret != null)
                bookIdMap.put(bookID, ret);
        }
        return ret;
    }
}
